import { useMutation } from '@tanstack/vue-query'
import { type Ref, ref } from 'vue'
import { useRoute } from 'vue-router'

import type { CellSlotProps } from './useDecodeTable'
import { queryClient } from '@/apis/client'
import { useGetReportQueryKey } from '@/apis/report'
import { ApiExecuteMimoDecode, type MimoDecodeArgs, ModulationMode, labMessage } from '@/apis/lab'
import { useFetchMessage } from '@/composables/useFetchMessage'
import { LabID } from '@/constants/lab'

export function useDecodeTableForm(reportID: Ref<number>) {
  const record = ref<Omit<MimoDecodeArgs, 'bitStream'> & { bitStream: string }>({
    index: 0,
    bitStream: '',
    receiveAntennas: 1,
    modulationMode: ModulationMode.FourASK,
    noiseRate: 0
  })

  const toggleRecord = (data: CellSlotProps['record']) => {
    record.value = {
      index: +data.key,
      bitStream: data.bitStream,
      receiveAntennas: data.receiveAntennas,
      modulationMode: data.modulationMode,
      noiseRate: data.noiseRate
    }
  }
  const cancel = () => {
    record.value.index = 0
  }

  const { showMessage } = useFetchMessage([labMessage])
  const { mutate } = useMutation({
    mutationFn: ApiExecuteMimoDecode,
    onSettled(data, error) {
      showMessage(data?.code ?? error?.data?.code)
    },
    onSuccess() {
      cancel()
      queryClient.invalidateQueries({ queryKey: useGetReportQueryKey(reportID) })
    }
  })

  const route = useRoute()
  const handleSubmit = () => {
    mutate({
      classID: +route.params.classID,
      experimentID: LabID.MIMOSimulator,
      args: {
        ...record.value,
        bitStream: Number.parseInt(record.value.bitStream, 2)
      }
    })
  }

  return {
    record,

    cancel,
    handleSubmit,
    toggleRecord
  }
}
